package demo.practice.leetcode_eveyday;

import demo.practice.Node;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

class LinkNode {
    LinkNode befor;
    LinkNode next;
    Integer value;

    LinkNode(Integer value) {
        this.value = value;
    }

}

public class P1743 {
    public static void main(String[] args) {
        P1743 p1743 = new P1743();
        p1743.restoreArray(new int[][]{{2, 1}, {3, 4}, {3, 2}});
    }

    public int[] restoreArray(int[][] adjacentPairs) {

        Map<Integer, LinkNode> map = new HashMap<>();
        for (int[] adjacentPair : adjacentPairs) {
            int first = adjacentPair[0];
            int second = adjacentPair[1];

            if (!map.containsKey(first)) {
                map.put(first, new LinkNode(first));
            }

            if (!map.containsKey(second)) {
                map.put(second, new LinkNode(second));
            }

            LinkNode f = map.get(first);
            LinkNode s = map.get(second);

            if (f.next == null && f.befor == null) {
                if (s.next == null) {
                    s.next = f;
                    f.befor = s;
                } else {
                    s.befor = f;
                    f.next = s;
                }
            } else if (f.next == null) {
                if (s.befor != null) {
                    s.befor.befor = s;
                    s.next = s.befor;
                }
                f.next = s;
                s.befor = f;
            } else {

                if (s.next != null) {
                    s.next.next=s;
                    s.befor = s.next;
                }
                f.befor = s;
                s.next = f;
            }
            System.out.println("xx");

        }

        Map.Entry<Integer, LinkNode> next = map.entrySet().iterator().next();
        LinkNode feed = next.getValue();
        LinkedList<Integer> list = new LinkedList<>();
        list.add(feed.value);
        LinkNode bf = feed;
        LinkNode ne = feed;

        while (bf.befor != null) {
            list.addFirst(bf.befor.value);
            bf = bf.befor;
        }

        while (ne.next != null) {
            list.addFirst(ne.next.value);
            ne = ne.next;
        }

        int[] res = new int[list.size()];
        int c = 0;
        for (Integer i : list) {
            res[c] = i;
            c++;
        }
        return res;
    }
}
